/**
 * Created by jaliu on 2015/2/28.
 */

var lotteries = mongoose.model('backoffice_lotteries');
var toolUtil = require('../../common/utils/toolUtil');
var async = require('async');
var Question = mongoose.model('question');
var Users = mongoose.model('user');
var giftActivities = mongoose.model('backoffice_giftActivities');
var moment = require('moment');
var participants = mongoose.model('backoffice_participants');
var userService = require('../userService');
var ugcIndex = mongoose.model('system_ugcIndex');

/**
 * Create a Lottery
 * @param input
 * @param callback
 */
exports.addWeekLotteryService = function (input, callback) {
    lotteries.findOne().exec(function (err, result) {
        var start = input.startTime;
        var end = input.endTime;
        var weekTemp = {
            startTime: start,
            endTime: end
        };
        result.weekLottery.push(weekTemp);
        result.save(callback);
    });
};

/**
 * Remove a lottery
 * @param loginId
 * @param callback
 */
exports.deleteLotteryService = function (lotteryObjId, callback) {
    lotteries.findOneAndRemove({_id: lotteryObjId}, callback);
};

/**
 * Update a lottery
 * @param lotteryObjId
 * @param input
 * @param callback
 */
exports.lotteryUpdateService = function (lotteryObjId, input, callback) {
    //lotteries.update({lotteryObjId: loginId},
    //    {
    //        $set:{
    //            'userName':input.userName,
    //            'role':input.role,
    //            'password':input.password
    //        }
    //    }, callback);
};

/**
 * Find a lottery
 * @param lotteryObjId
 * @param callback
 */
exports.lotteryFindById = function (lotteryObjId, callback) {
    lotteries.findById(id).exec(callback);
};

/**
 * List all lottery
 * @param callback
 */
exports.lotteryListAllService = function (lotteryName, callback) {
    lotteries.find({}).sort('lotteryStartDate').exec(callback);
};

/**
 * Validate user is valid or not for a specific lottery
 * @param token
 * @param lotteryObjId
 * @param callback
 */
exports.validateUserForLotteryService = function (token, lotteryObjId, callback) {

    var userT;

    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            async.series([
                function (callbackInner) {
                    Users.findOne({_id: user._id}, 'mobilePhone apartmentDetail authenticationStatus roomUnit roomNumber', function (err, result) {
                        userT = result;
                        callbackInner(null, result.authenticationStatus);
                    });
                },
                function (callbackInner) {
                    var date = moment().startOf("week");


                    Question.findOne({
                        $or: [{'createdBy': user._id}, {'replies.repliedBy': user._id}],
                        dateCreated: {$gte: date}
                    }, '_id desc', function (err, result) {
                        if (result == null) {
                            callbackInner(err, false);
                        } else {
                            callbackInner(err, true);
                        }
                    })
                },
                function (callbackInner) {
                    lotteries.findOne({_id: lotteryObjId}, 'weekLottery', function (err, result) {
                        var now = new Date();
                        var joinedUser = 0;
                        var data = {};

                        var date;

                        var flag = true;

                        if (result != null && result.weekLottery != null) {
                            result.weekLottery.forEach(function (lottery) {
                                if (lottery.startTime < now && lottery.endTime > now) {
                                    date = lottery.endTime;
                                    if (lottery.lotteryTickets != null) {
                                        joinedUser = lottery.lotteryTickets.length;

                                        lottery.lotteryTickets.forEach(function (tic) {
                                            if (tic.user == user._id) {
                                                data['ticketValue'] = tic.ticketValue;
                                                data['address'] = tic.address;
                                                data['phone'] = tic.phone;
                                                data['roomUnit'] = userT.roomUnit;
                                                data['roomNumber'] = userT.roomNumber;
                                                data['userName'] = tic.userName;
                                                data['joinedUser'] = joinedUser;
                                                data['lotteryTime'] = lottery.endTime;
                                                flag = false;
                                                callbackInner(err, data);
                                            }
                                        });
                                    }
                                }
                            })
                        }

                        if (flag) {
                            participants.findOne({user: user._id}, 'mobilePhone userName address roomUnit roomNumber', function (err, res) {
                                if (res != null) {
                                    data['userName'] = res.userName;
                                    data['address'] = res.address;
                                    data['phone'] = res.mobilePhone;
                                    data['roomUnit'] = (userT.roomUnit);
                                    data['roomNumber'] = (userT.roomNumber);
                                } else {
                                    data['address'] = userT.apartmentDetail;
                                    data['phone'] = userT.mobilePhone;
                                    data['roomUnit'] = (userT.roomUnit);
                                    data['roomNumber'] = (userT.roomNumber);
                                }
                                data['authenticationStatus'] = userT.authenticationStatus;
                                data['joinedUser'] = joinedUser;
                                data['lotteryTime'] = date;
                                callbackInner(err, data);
                            })
                        }
                    })
                }
            ], callback)
        }
    });
};

/**
 * Generate a lottery ticket for user for a specific lottery
 * @param token
 * @param lotteryObjId
 * @param input
 * @param callback
 */
exports.generateLotteryTicketForUserService = function (token, lotteryObjId, input, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            lotteries.findOne({_id: lotteryObjId}, 'weekLottery', function (err, result) {
                var now = new Date();
                var joinedUser = 0;
                if (result != null) {
                    if (result.weekLottery != null) {
                        var weekFlag = true;
                        result.weekLottery.forEach(function (lottery) {
                            if (lottery.startTime < now && lottery.endTime > now) {
                                weekFlag = false;
                                if (lottery.lotteryTickets != null) {
                                    var flag = true;
                                    joinedUser = lottery.lotteryTickets.length;
                                    lottery.lotteryTickets.forEach(function (tic) {
                                        if (tic.user == user._id) {
                                            var msg = {
                                                "message": "你已经参与抽奖"
                                            };
                                            flag = false;
                                            var data = {
                                                joinedUser: joinedUser,
                                                ticketValue: tic.ticketValue
                                            };
                                            callback(msg, data);
                                        }
                                    });
                                    if (flag) {
                                        var key = 'a:' + user.community._id + ':' + Math.round(lottery.startTime.getTime() / 1000);
                                        toolUtil.generateLotteryTickets(key, function (err, value) {
                                            if (err) {
                                                callback(err, null);
                                            } else {
                                                var temp = {
                                                    user: user._id,
                                                    ticketValue: value,
                                                    userName: input.userName,
                                                    phone: input.phone,
                                                    address: input.address,
                                                    roomUnit: input.roomUnit,
                                                    roomNumber: input.roomNumber
                                                };
                                                lottery.lotteryTickets.push(temp);
                                                result.save(function (err, r) {
                                                    var data = {
                                                        joinedUser: joinedUser + 1,
                                                        ticketValue: temp.ticketValue
                                                    };
                                                    callback(err, data);
                                                    /*宝宝树66小区二次改造    mod   zhangm  20170714   start*/
                                                    /*var message = '梦想还是要有的，万一实现了呢？66小区周周有惊喜，每月中大奖，请谨记您的中奖号：' + value + '，每周准点开奖，祝您拿大奖';*/
                                                    var message = '梦想还是要有的，万一实现了呢？宝宝树66小区周周有惊喜，每月中大奖，请谨记您的中奖号：' + value + '，每周准点开奖，祝您拿大奖';
                                                    /*宝宝树66小区二次改造    mod   zhangm  20170714   start*/

                                                    toolUtil.pushCustomerServiceMessage(user, message);

                                                    participants.remove({user: user._id}, function (err, result) {
                                                        var temp = new participants();
                                                        temp.userName = input.userName;
                                                        temp.mobilePhone = input.phone;
                                                        temp.address = input.address;
                                                        temp.roomUnit = input.roomUnit;
                                                        temp.roomNumber = input.roomNumber;
                                                        temp.user = user._id;
                                                        temp.save();
                                                    });
                                                    var t = {
                                                        roomUnit: input.roomUnit,
                                                        roomNumber: input.roomNumber,
                                                        apartmentDetail: input.address
                                                    };
                                                    userService.updateService(user._id, t, function (err, result) {
                                                    });
                                                });
                                            }
                                        })
                                    }
                                }
                            }
                        });
                        if (weekFlag) {

                            var msg = {
                                "message": "活动未开始"
                            };

                            callback(msg, null);

                            //var start = moment().startOf("week").add(-13, 'hours').format('YYYY-MM-DD HH:mm:ss')
                            //var end = moment().startOf("week").add(6, 'days').add(11, 'hours');
                            //
                            //toolUtil.generateLotteryTickets(start, function (err, value) {
                            //    if (err) {
                            //        callback(err, null)
                            //    } else {
                            //        var temp = {
                            //            user: user._id,
                            //            ticketValue: value,
                            //            userName: input.userName,
                            //            phone: input.phone,
                            //            address: input.address
                            //        };
                            //        var weekTemp = {
                            //            startTime: start,
                            //            endTime: end,
                            //            lotteryTickets: [temp]
                            //        };
                            //        result.weekLottery.push(weekTemp);
                            //        result.save(function (err, r) {
                            //            var data = {
                            //                joinedUser: 1,
                            //                ticketValue: temp.ticketValue
                            //            };
                            //            callback(err, data);
                            //        });
                            //    }
                            //});
                        }
                    }
                }
            })
        }
    });
};

exports.getLuckyUserListService = function (lotteryObjId, callback) {
    lotteries.findOne({_id: lotteryObjId})
        .populate('weekLottery.lotteryTickets.user', 'nickName images roomUnit').exec(function (err, result) {
            var data = new Array();
            if (result != null && result.weekLottery != null) {

                async.eachSeries(result.weekLottery, function (lottery, callbackIn) {
                    if (lottery.lotteryTickets != null && lottery.isOpen) {
                        var weekData = [];

                        async.each(lottery.lotteryTickets, function (tic, callbackInner) {
                            if (tic.isLucky) {
                                var imageURL = '';
                                if (tic.user.images != null && tic.user.images.length > 0) {
                                    imageURL = tic.user.images[0].imageURL;
                                }
                                var temp = {
                                    profileImage: imageURL,
                                    userName: tic.user.nickName,
                                    address: tic.address,
                                    roomUnit: tic.user.roomUnit,
                                    prize: tic.prize,
                                    ranking: tic.ranking
                                };
                                switch (tic.ranking) {
                                    case 6:
                                        temp.level = '一等奖';
                                        break;
                                    case 5:
                                    case 4:
                                        temp.level = '二等奖';
                                        break;
                                    case 3:
                                    case 2:
                                    case 1:
                                        temp.level = '三等奖';
                                        break;
                                }

                                Question.count({
                                    createdBy: tic.user._id,
                                    dateCreated: {$gte: lottery.startTime, $lt: lottery.endTime}
                                }, function (err, count) {
                                    temp.questionCount = count;
                                    weekData.push(temp);
                                    callbackInner();
                                });
                            } else {
                                callbackInner();
                            }
                        }, function (err) {
                            weekData.sort(function (a, b) {
                                return b.ranking - a.ranking;
                            });
                            var dataItem = {
                                date: moment(lottery.endTime).format('MM月DD日'),
                                uList: weekData
                            };

                            data.push(dataItem);
                            callbackIn()
                        });
                    } else {
                        callbackIn()
                    }
                }, function (err) {
                    data.forEach(function (temp, i) {
                        temp.week = '第' + (i + 1) + '周榜单'
                    });

                    data.reverse();
                    callback(err, data);
                });
            }
        });
};

exports.getLcLuckyUserListService = function (lotteryObjId, week, callback) {

    var format = '?imageView2/2/format/jpg';

    week = Number(week);

    lotteries.findOne({_id: lotteryObjId})
        .populate('weekLottery.lotteryTickets.user', 'nickName images roomUnit').exec(function (err, result) {
            var data = [];
            if (result != null && result.weekLottery != null) {

                async.eachSeries(result.weekLottery, function (lottery, callbackIn) {
                    if (lottery.lotteryTickets != null && lottery.isOpen) {
                        var weekData = [];

                        async.each(lottery.lotteryTickets, function (tic, callbackInner) {
                            if (tic.isLucky) {
                                var imageURL = '';
                                if (tic.user.images != null && tic.user.images.length > 0) {
                                    imageURL = tic.user.images[0].imageURL;
                                }

                                if (imageURL.indexOf('http://') != 0) {
                                    imageURL = 'http://' + imgHost + imageURL + format;
                                }

                                var temp = {
                                    profileImage: imageURL,
                                    userName: tic.user.nickName,
                                    address: tic.address,
                                    roomUnit: tic.user.roomUnit,
                                    prize: tic.prize,
                                    ranking: tic.ranking
                                };
                                switch (tic.ranking) {
                                    case 6:
                                        temp.level = '一等奖';
                                        break;
                                    case 5:
                                    case 4:
                                        temp.level = '二等奖';
                                        break;
                                    case 3:
                                    case 2:
                                    case 1:
                                        temp.level = '三等奖';
                                        break;
                                }
                                weekData.push(temp);
                                callbackInner();
                            } else {
                                callbackInner();
                            }
                        }, function (err) {
                            weekData.sort(function (a, b) {
                                return b.ranking - a.ranking;
                            });
                            var dataItem = {
                                date: moment(lottery.endTime).format('MM月DD日'),
                                uList: weekData
                            };

                            data.push(dataItem);
                            callbackIn()
                        });
                    } else {
                        callbackIn()
                    }
                }, function (err) {
                    data.forEach(function (temp, i) {
                        temp.week = '第' + (i + 1) + '周榜单'
                    });

                    data.reverse();
                    if (data[week] != null) {
                        callback(null, [data[week]])
                    } else {
                        callback(null, []);
                    }
                });
            }
        });
}

exports.lotteryUserService = function (lotteryId, weekId, rank, callback) {
    var user = null;
    lotteries.findOne({_id: lotteryId}).populate('weekLottery.lotteryTickets.user', '_id nickName images roomUnit roomNumber mobilePhone').exec(function (err, result) {

        async.each(result.weekLottery, function (lottery, callbackInner) {
            if (lottery._id == weekId) {
                var key = 'a:' + result.community + ':' + Math.round(lottery.startTime.getTime() / 1000);
                logger.info(key);

                async.each(lottery.lotteryTickets, function (tic, c1) {
                    ugcIndex.count({
                        createdBy: tic.user._id,
                        dateCreated: {$gt: lottery.startTime, $lt: lottery.endTime}
                    }, function (err, count) {
                        tic.user.count = count;
                        c1();
                    });
                }, function (err) {
                    var pop = function (key, lottery, callbackInner) {
                        redisClient.spop(key + ':pool', function (err, value) {
                            if (value == null) {
                                callbackInner(null, null)
                            } else {
                                redisClient.sadd(key + ':discard', value);
                                lottery.lotteryTickets.forEach(function (tic) {
                                    if (tic._doc.ranking == rank) {
                                        tic.isLucky = false;
                                        tic.ranking = 0;
                                        tic.prize = undefined;
                                    }
                                    if (tic.user.mobilePhone == null) {
                                        tic.user.mobilePhone = 'test';
                                    }

                                    if (tic._doc.ticketValue == value) {
                                        if (tic.user.mobilePhone.indexOf('400400') == 0 || tic.user.count < 3) {
                                            pop(key, lottery, callbackInner);
                                        } else {
                                            tic.isLucky = true;
                                            tic.ranking = rank;
                                            user = tic;
                                            switch (Number(rank)) {
                                                case 6:
                                                    tic.prize = lottery.firstPrize;
                                                    break;
                                                case 5:
                                                    tic.prize = lottery.twoPrize;
                                                    break;
                                                case 4:
                                                    tic.prize = lottery.twoPrize;
                                                    break;
                                                case 3:
                                                    tic.prize = lottery.threePrize;
                                                    break;
                                                case 2:
                                                    tic.prize = lottery.threePrize;
                                                    break;
                                                case 1:
                                                    tic.prize = lottery.threePrize;
                                                    break;
                                            }

                                            result.save(function (err, result) {
                                                callbackInner(null, null)
                                            });
                                        }
                                    }
                                });
                            }
                        })
                    }
                    pop(key, lottery, callbackInner)
                });

                //redisClient.spop(key + ':pool', function (err, value) {
                //    if (value == null) {
                //        callbackInner(null, null)
                //    } else {
                //        redisClient.sadd(key + ':discard', value);
                //        lottery.lotteryTickets.forEach(function (tic) {
                //            if (tic._doc.ranking == rank) {
                //                tic.isLucky = false;
                //                tic.ranking = 0;
                //                tic.prize = undefined;
                //            }
                //            if (tic._doc.ticketValue == value) {
                //                tic.isLucky = true;
                //                tic.ranking = rank;
                //                user = tic;
                //                switch (Number(rank)) {
                //                    case 6:
                //                        tic.prize = lottery.firstPrize;
                //                        break;
                //                    case 5:
                //                        tic.prize = lottery.twoPrize;
                //                        break;
                //                    case 4:
                //                        tic.prize = lottery.twoPrize;
                //                        break;
                //                    case 3:
                //                        tic.prize = lottery.threePrize;
                //                        break;
                //                    case 2:
                //                        tic.prize = lottery.threePrize;
                //                        break;
                //                    case 1:
                //                        tic.prize = lottery.threePrize;
                //                        break;
                //                }
                //            }
                //        });
                //        result.save(function (err, result) {
                //            callbackInner(null, null)
                //        });
                //    }
                //})
            } else {
                callbackInner(null, null);
            }
        }, function (err) {
            callback(err, user);
        });
    });
};

exports.getLuckyUserService = function (lotteryId, weekId, callback) {
    async.waterfall([
        function (callbackInner) {
            var user = {};
            lotteries.findOne({_id: lotteryId}).exec(function (err, result) {
                result.weekLottery.forEach(function (lottery) {
                    if (lottery._id == weekId) {
                        lottery.lotteryTickets.forEach(function (tic) {
                            if (tic.isLucky) {
                                user = {
                                    "userId": tic.user,
                                    "userName": tic.userName
                                }
                            }
                        });
                    }
                });
                callbackInner(err, user)
            });
        },
        function (user, callbackInner) {
            Users.findById(user.userId, 'userName email mobilePhone birthDate nickName age gender maritalStatus hasChildren images apartmentDetail hobbies community homeTown.country homeTown.province homeTown.city homeTown.county huanxinUserName appSetting userType speciality userPortrait job school authenticationStatus')
                .populate('userPortrait', 'portraitURL value').populate('community', '_id communityName communityAddress').populate('homeTown.country', '_id name').populate('homeTown.province', '_id name').populate('homeTown.city', '_id name').populate('homeTown.county', '_id name').populate('hobbies', '_id value')
                .exec(function (err, result) {
                    result._doc['userName'] = user.userName;
                    callbackInner(err, result);
                });
        }
    ], callback)
};

/**
 * 开奖
 * @param lotteryId
 * @param weekId
 * @param callback
 */
exports.openLotteryService = function (lotteryId, weekId, callback) {

    if (lotteryId != '54f1d53b6383f85024d1ea26') {
        lotteries.findOne({_id: lotteryId}).exec(function (err, result) {
            result.weekLottery.forEach(function (lottery) {
                if (lottery._id == weekId) {
                    lottery.isOpen = true;
                    lottery.endTime = new Date();

                    lottery.lotteryTickets.forEach(function (tic) {
                        if (tic.isLucky) {

                            Users.findOne({_id: tic.user}, '_id huanxinUserName nickName community').populate('community', '_id communityName').exec(function (err, user) {
                                var nickName = '';
                                if (user.nickName != null) {
                                    nickName = user.nickName;
                                }
                                var message = "尊敬的用户" + nickName + "，恭喜您获得了宝宝树66小区本周幸运大奖，稍后小6客服将通过站内私信，电话/短信等方式联系您确认奖品发放事宜，请上宝宝树66小区APP并保持手机通畅。提醒，本次活动宝宝树66小区不会向中奖用户索取任何费用，谨防受骗。"
                                if (message != null) {
                                }
                                //toolUtil.pushCustomerServiceMessage(user, message);
                            })
                        }
                    });
                }
            });

            if (result.weekday == null)
                result.weekday = 6;
            if (result.time == null)
                result.time = 11;

            var start = new Date();
            var end = moment().startOf("week").add((7 + result.weekDay), 'days').add(result.time, 'hours');
            var weekTemp = {
                startTime: start,
                endTime: end,
                firstPrize: 'ipad'
            };
            result.weekLottery.push(weekTemp);
            result.save(callback);
        });
    } else {
        lotteries.findOne({_id: lotteryId}).exec(function (err, result) {
            result.weekLottery.forEach(function (lottery) {
                if (lottery._id == weekId) {
                    lottery.isOpen = true;
                    lottery.endTime = new Date();

                    lottery.lotteryTickets.forEach(function (tic) {
                        if (tic.isLucky) {

                            Users.findOne({_id: tic.user}, '_id huanxinUserName nickName community').populate('community', '_id communityName').exec(function (err, user) {
                                var nickName = '';
                                if (user.nickName != null) {
                                    nickName = user.nickName;
                                }
                                var message;

                                message = "尊敬的用户" + nickName + "，恭喜您获得了宝宝树66小区本周幸运大奖，稍后小6客服将通过站内私信，电话/短信等方式联系您确认奖品发放事宜，请上宝宝树66小区APP并保持手机通畅。提醒，本次活动宝宝树66小区不会向中奖用户索取任何费用，谨防受骗。"
                                if (message != null) {
                                }
                                //toolUtil.pushCustomerServiceMessage(user, message);
                            })
                        }
                    });
                }
            });

            if (result.weekday == null)
                result.weekday = 6;
            if (result.time == null)
                result.time = 11;

            var start = new Date();
            var end = moment().startOf("week").add((7 + result.weekDay), 'days').add(result.time, 'hours');
            var weekTemp = {
                startTime: start,
                endTime: end,
                firstPrize: 'ipad'
            };
            result.weekLottery.push(weekTemp);
            result.save(callback);
        });
    }
};

exports.getLotteryActivityService = function (communityId, callback) {
    lotteries.findOne({community: communityId}).populate('weekLottery.lotteryTickets.user', 'nickName images roomUnit roomNumber').exec(function (err, result) {
        if (result != null) {
            async.each(result.weekLottery, function (lot, c2) {
                async.each(lot.lotteryTickets, function (tic, c1) {
                    ugcIndex.count({
                        createdBy: tic.user._id,
                        dateCreated: {$gte: lot.startTime, $lt: lot.endTime}
                    }, function (err, count) {
                        tic.user._doc['count'] = count;
                        c1();
                    })
                }, function (err) {
                    c2();
                })
            }, function (err) {
                callback(err, result)
            })
        } else {
            callback(err, null);
        }
    });
};


/**
 * generate all tickets for a lottery
 * @param lotteryObjId
 * @param callback
 */
exports.generateLotteryTickets = function (lotteryObjId, callback) {
    //if there is user already allocated, then cannot generate
}

/**
 * To update the gift status for a user and a lottery
 * @param userObjId
 * @param lotteryObjId
 * @param callback
 */
exports.lotteryGiftSendOutStatusUpdate = function (userObjId, lotteryObjId, callback) {

};


exports.getUserInfoService = function (token, activityId, callback) {

    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            var data = {};
            var flag = true;

            Users.findOne({_id: user._id}, 'mobilePhone apartmentDetail authenticationStatus roomUnit roomNumber', function (err, userT) {

                giftActivities.findOne({_id: activityId}, 'users', function (err, activity) {
                    if (activity != null && activity.users != null) {
                        activity.users.forEach(function (u) {
                            if (u.user == user._id) {
                                data['submittedFlag'] = true;
                                data['address'] = u.apartmentDetail;
                                data['roomUnit'] = userT.roomUnit;
                                data['roomNumber'] = userT.roomNumber;
                                data['phone'] = u.mobilePhone;
                                data['userName'] = u.userName;
                                data['timePeriodAvailable'] = u.timePeriodAvailable;
                                flag = false;
                                callback(err, data);
                            }
                        });
                    }
                    if (flag) {
                        participants.findOne({user: user._id}, 'mobilePhone address userName roomUnit roomNumber', function (err, res) {
                            if (res != null) {
                                data['address'] = res.address;
                                data['userName'] = res.userName;
                                data['phone'] = res.mobilePhone;
                                data['roomUnit'] = userT.roomUnit;
                                data['roomNumber'] = userT.roomNumber;
                            } else {
                                data['address'] = userT.apartmentDetail;
                                data['phone'] = userT.mobilePhone;
                                data['roomUnit'] = userT.roomUnit;
                                data['roomNumber'] = userT.roomNumber;
                            }
                            data['submittedFlag'] = false;
                            data['authenticationStatus'] = userT.authenticationStatus;
                            callback(err, data);
                        });
                    }
                });
            });
        }
    });
};

exports.doRegisterActivityService = function (token, activityId, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (user == null) {
            var msg = {
                "message": noUserErrMessage
            };
            callback(msg, null);
        } else {
            var flag = true;
            giftActivities.findOne({_id: activityId}, 'users', function (err, activity) {
                if (activity != null && activity.users != null) {
                    activity.users.forEach(function (u) {
                        if (u.user == user._id) {
                            var msg = {
                                "message": "用户已报名"
                            };
                            flag = false;
                            callback(msg, null);
                        }
                    });
                }
                if (flag) {
                    var temp = {
                        "user": user._id,
                        "userName": input.userName,
                        "mobilePhone": input.phone,
                        "apartmentDetail": input.address,
                        "roomUnit": input.roomUnit + '',
                        "roomNumber": input.roomNumber + '',
                        "timePeriodAvailable": input.timePeriodAvailable
                    };
                    async.series([
                        function (callbackInner) {
                            giftActivities.update({_id: activityId}, {$push: {'users': temp}}).exec(callbackInner);
                        },
                        function (callbackInner) {

                            var data = {
                                roomUnit: input.roomUnit + '',
                                roomNumber: input.roomNumber + '',
                                apartmentDetail: input.address
                            };
                            userService.updateService(user._id, data, callbackInner);
                        },
                        function (callbackInner) {
                            participants.remove({user: user._id}, callbackInner);
                        },
                        function (callbackInner) {
                            var temp = new participants();
                            temp.userName = input.userName;
                            temp.mobilePhone = input.phone;
                            temp.address = input.address;
                            temp.roomUnit = input.roomUnit + '';
                            temp.roomNumber = input.roomNumber + '';
                            temp.user = user._id;
                            temp.save(callbackInner);
                        }
                    ], callback)
                }
            });
        }
    });
};